#include "tcpserver.h"

TcpServer::TcpServer(QHostAddress addr, int port, Hrac * hrac)
{
    zakladajiciHrac = hrac;
    server = new QTcpServer(this);
    connect(server, SIGNAL(newConnection()), this, SLOT(NewConnection()));
    server->setProxy(QNetworkProxy::NoProxy);
    listening = server->listen(addr, port);


}

void TcpServer::newConnection()
{
    QTcpSocket* socket = server->nextPendingConnection();
    if(!socket) return;

    connect(socket, SIGNAL(readyRead()), SLOT(reply()));

    connect(socket, SIGNAL(disconnected()), SLOT(gotDisconnected()));

    this->sendHi(socket, zakladajiciHrac);
}

void TcpServer::reply()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(this->sender());
    QByteArray rawdata = socket->readAll();
    QList<QByteArray> args = rawdata.split(';');
    QString command = args.takeFirst();
    QDataStream stream(args.takeFirst());

    if (command =="HI")
    {
        Hrac * hrac = new Hrac(stream);
        emit new_Hrac_data(hrac);
    }
    else if (command =="TAH")
    {
        Tah * tah = new Tah(stream);
        emit new_Tah_data(tah);
    }
    else if (command =="NEWGAME")
    {
        emit new_game_requested();
    }
}

void TcpServer::got_Disconnected()
{

}

void TcpServer::socketWrite(QTcpSocket *socket, QByteArray data)
{
    socket->write(data);
    socket->flush();
}

void TcpServer::sendHi(QTcpSocket *socket, Hrac *hrac)
{
    QByteArray tmp;
    QDataStream out(&tmp, QIODevice::WriteOnly);
    hrac->serialize(out);
    tmp.prepend("HI;");
    this->socketWrite(socket,tmp);
}

void TcpServer::sendTah(QTcpSocket *socket, Tah *tah)
{
    QByteArray tmp;
    QDataStream out(&tmp, QIODevice::WriteOnly);
    tah->serialize(out);
    tmp.prepend("TAH;");
    this->socketWrite(socket,tmp);
}

void TcpServer::sendNewgame(QTcpSocket *socket)
{
    this->socketWrite(socket, "NEWGAME;");
}
